import { getWebSocketUrl } from '../utils/auth';
import CryptoJS from 'crypto-js';

// 定义消息类型
export interface AIMessage {
  role: 'user' | 'assistant';
  content: string;
}

// 调用星火大模型（WebSocket 流式响应）
export const getAIResponseStream = async (
  messages: AIMessage[],
  onMessage: (text: string) => void,
  onClose: () => void
) => {
  const url = await getWebSocketUrl();
  const ws = new WebSocket(url);

  ws.onopen = () => {
    const payload = {
      header: {
        app_id: "YOUR_APP_ID",
        uid: "user123"
      },
      parameter: {
        chat: {
          domain: "generalv2",  // 根据版本选择
          temperature: 0.5,
          max_tokens: 2048
        }
      },
      payload: {
        message: {
          text: messages
        }
      }
    };
    ws.send(JSON.stringify(payload));
  };

  let fullText = '';
  ws.onmessage = (event) => {
    const res = JSON.parse(event.data);
    const content = res.payload.choices.text[0].content;
    if (content) {
      fullText += content;
      onMessage(fullText);
    }
    
    // 状态码 2 表示结束
    if (res.header.code === 2) {
      ws.close();
      onClose();
    }
  };

  ws.onerror = (error) => {
    console.error('WebSocket Error:', error);
    onMessage('服务请求失败，请重试');
    onClose();
  };
};